package group.igfd.manager.biz.controller;

import group.igfd.manager.biz.oss.AliyunOSSClientConstant;
import group.igfd.manager.biz.oss.UploadServices;
import group.igfd.manager.biz.utils.FileUtil;
import group.igfd.manager.biz.utils.IdGenerator;
import io.renren.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.*;


@RestController
@RequestMapping("biz/upload")
@Api(tags = {"A002/ 文件上传"})
public class UploadController {

    private Logger logger = LoggerFactory.getLogger(UploadController.class);
    @Autowired
    private UploadServices uploadServices;

    @PostMapping(value = {"/upimg"})
    @ApiOperation(value = "上传图片", notes = "上传图片")
    @ResponseBody
    public R uploadIMG(@RequestParam("file") MultipartFile[] multipartFile, HttpServletRequest request) throws Exception{

        if (null != multipartFile && multipartFile.length > 0) {

            List<String> urlList=new ArrayList<String>();
            //遍历并保存文件
            for (MultipartFile files : multipartFile) {
                if (multipartFile != null) {
                    // 获取文件名
                    String fileName = files.getOriginalFilename();
                    // 获取文件后缀
                    String prefix=fileName.substring(fileName.lastIndexOf("."));
                    //新建临时文件
                    File img = File.createTempFile(IdGenerator.getId(), prefix);
                    //写入inputStream
                    FileInputStream inputStream=(FileInputStream)files.getInputStream();
                    FileUtil.inputStream2ToFile(inputStream,img);

                    logger.info(img.getPath());
                    // 上传aliyun oss
                    String ossurl = uploadServices.uploadImgToOSS(img);
                    logger.info(ossurl);
                    urlList.add(ossurl);

                }
            }
            return R.ok();

        } else {
            return R.error("上传失败");
        }


    }

    @RequestMapping(value = {"/upimgSingle"}, method={RequestMethod.OPTIONS, RequestMethod.POST})
    @ApiOperation(value = "上传单张图片", notes = "上传单张图片 module_type有-> avatar:头像，customer_post:客人不发布，buyer_post:买手发布，experts_post:达人发布，realName:实名认证，orderInfo:订单相关的上传")
    @ResponseBody
    public R uploadIMGSingle(@RequestParam("file") MultipartFile multipartFile,
                                        @RequestParam("module_type") String module_type) throws Exception{
//

        if (StringUtils.isEmpty(multipartFile) || StringUtils.isEmpty(module_type)){
            return R.error("参数不能为空");
        }

        if (null != multipartFile) {

            if (!"avatar".equals(module_type) && !"customer_post".equals(module_type)
                    && !"buyer_post".equals(module_type) && !"experts_post".equals(module_type)
                    && !"realName".equals(module_type) && !"orderInfo".equals(module_type)) {
                return R.error("参数错误");
            }

            // 获取文件名
            String fileName = multipartFile.getOriginalFilename();
            // 获取文件后缀
            String prefix=fileName.substring(fileName.lastIndexOf("."));
            //新建临时文件
            File img = File.createTempFile(IdGenerator.getId(), prefix);
            //写入inputStream
            FileInputStream inputStream=(FileInputStream)multipartFile.getInputStream();
            FileUtil.inputStream2ToFile(inputStream,img);

            String ossurl;

            // 上传aliyun oss
            if ("orderInfo".equals(module_type)) {
                ossurl = uploadServices.uploadInvoiceToOSS(img);
            } else {
                ossurl = uploadServices.uploadImgToOSS(img);
            }

            logger.info(ossurl);

            //图片相对地址
            String resImgUrl= new URL(ossurl).getPath();

            //绝对地址
            String absoluteAddress;
            if ("orderInfo".equals(module_type)) {
                absoluteAddress = AliyunOSSClientConstant.ALIYUN_IMAGEURL_PRE_STYLE + resImgUrl + AliyunOSSClientConstant.ALIYUN_IMAGEURL_SUFF_STYLE;
            } else {
                absoluteAddress = AliyunOSSClientConstant.ALIYUN_IMAGEURL_PRE + resImgUrl + AliyunOSSClientConstant.ALIYUN_IMAGEURL_SUFF;
            }

            //组装返回结果
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("url",absoluteAddress);

            return R.ok(resultData);

        } else {
            return R.error("上传文件不能为空");
        }
    }
}
